package com.ajmd.onlineexam.service;

import com.ajmd.onlineexam.entity.*;
import com.ajmd.onlineexam.enumeration.StaticFinalValue;
import com.ajmd.onlineexam.mapper.FolderMapper;
import com.ajmd.onlineexam.mapper.QuestionMapper;
import com.ajmd.onlineexam.mapper.TestPaperMapper;
import com.ajmd.onlineexam.mapper.TestPaperQuestionMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author ajmd
 * @since 2023/4/4 19:54
 */
@Service
public class TestPaperService {
    @Resource
    private TestPaperMapper testPaperMapper;
    @Resource
    private TestPaperQuestionMapper testPaperQuestionMapper;
    @Resource
    private TestPaperQuestionService testPaperQuestionService;
    @Resource
    private FolderService folderService;
    @Resource
    private RedisTemplate redisTemplate;

    public TestPaperPO selectById(String id){
        return testPaperMapper.selectById(id);
    }

    public int addTestPaper(TestPaperPO testPaperPO){
        UUID uuid = UUID.randomUUID();
        testPaperPO.setId(uuid.toString());
        return testPaperMapper.insert(testPaperPO);
    }


    public Page<TestPaperPO> findByFolder(String belongFolderId, String account, SearchParam searchParam, Integer userType,
                                             Integer folderRange, Integer currentPage, Integer pageSize){
//        MPJLambdaWrapper<TestPaperPO> queryWrapper = new MPJLambdaWrapper<>();
        LambdaQueryWrapper<TestPaperPO> queryWrapper = new LambdaQueryWrapper<>();
        //如果是教师还需要做以下限制，否则是管理员不做限制（查看所有）
        if(StaticFinalValue.TEACHER.equals(userType)){
            if(StaticFinalValue.CLICK_ONLY_MY_FOLDERS.equals(folderRange)){
                //仅查看自己创建的
                Set<String> folderIds = folderService.getFolderIds(account);
                queryWrapper.eq(TestPaperPO::getCreatePerson,account)
                        .in(TestPaperPO::getBelongFolderId,folderIds);

            }else{
                //查看公开的和自己创建的
                queryWrapper.nested(
                        qw->qw.eq(TestPaperPO::getPublicRange, StaticFinalValue.PUBLIC)
                                .or()
                                .eq(TestPaperPO::getCreatePerson,account).eq(TestPaperPO::getPublicRange,StaticFinalValue.NOT_PUBLIC)

                );
            }
        }
        //belongFolderId不为空则进行文件夹限制；为空表示查询全部，无需加文件夹限制
        if (ObjectUtils.isNotEmpty(belongFolderId)){
            queryWrapper.like(TestPaperPO::getBelongFolderFullId,belongFolderId);
        }
        //搜索条件过滤
        if(ObjectUtils.isNotEmpty(searchParam)){
            if (ObjectUtils.isNotEmpty(searchParam.getSearchValue())){
                queryWrapper.like(TestPaperPO::getTestPaperName,searchParam.getSearchValue());
            }
            //创建时间过滤
            if(ObjectUtils.isNotEmpty(searchParam.getStartTime())){
                queryWrapper.between(TestPaperPO::getCreateTime,searchParam.getStartTime(),searchParam.getEndTime());
            }
        }

        queryWrapper.orderByDesc(TestPaperPO::getCreateTime);
        Page<TestPaperPO> page = new Page<>(currentPage,pageSize);
        return testPaperMapper.selectPage(page, queryWrapper);
//        return questionBankMapper.selectList(queryWrapper);
    }


    public int testPaperUpdate(TestPaperPO testPaperPO){
        return testPaperMapper.updateById(testPaperPO);
    }


    public int testPaperMove(List<String> testPaperIds,TestPaperPO testPaperPO,String account,Integer userType){
        LambdaQueryWrapper<TestPaperPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(userType.equals(StaticFinalValue.TEACHER)){
            lambdaQueryWrapper.eq(TestPaperPO::getCreatePerson,account);
        }
        lambdaQueryWrapper.in(TestPaperPO::getId,testPaperIds);
        return testPaperMapper.update(testPaperPO,lambdaQueryWrapper);
    }


    @Transactional
    public int testPaperDelete(List<String> testPaperIds, String account, Integer userType){
        LambdaQueryWrapper<TestPaperPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //不是超管不能删除其他人的试卷
        if(StaticFinalValue.TEACHER.equals(userType)){
            lambdaQueryWrapper.eq(TestPaperPO::getCreatePerson,account);
        }
        //先筛选出能删除的试卷
        lambdaQueryWrapper.in(TestPaperPO::getId,testPaperIds);
        List<TestPaperPO> testPaperPOS = testPaperMapper.selectList(lambdaQueryWrapper);
        List<String> canRemoveTestPaperIds = testPaperPOS.stream().map(TestPaperPO::getId).collect(Collectors.toList());
        //1，删除所有试卷下的试题、选项和图片
        //根据 testPaperIds 查询所有试卷试题id
        LambdaQueryWrapper<TestPaperQuestionPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TestPaperQuestionPO::getTestPaperId,testPaperIds);
        List<TestPaperQuestionPO> tPQuestionPOList = testPaperQuestionMapper.selectList(queryWrapper);
        List<String> tPQuestionIds = tPQuestionPOList.stream().map(TestPaperQuestionPO::getId).collect(Collectors.toList());
        //根据 tPQuestionIds 删除试题、选项和图片
        testPaperQuestionService.deleteTPQuestions(tPQuestionIds);

        //2，删除所有试卷
        //从redis中删除试卷
        for(String testPaperId:canRemoveTestPaperIds){
            redisTemplate.delete(testPaperId);
        }
        return testPaperMapper.deleteBatchIds(canRemoveTestPaperIds);
    }
}
